package tomoto.commandline;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import tomoto.util.IntHolder;

public class GetOpt {
	public static final int PARAMETRIC = 1;

	private List<String> m_args = new ArrayList<String>();
	private Map<String, String> m_options = new HashMap<String, String>();
	private Map<String, IntHolder> m_optionConfigs = new HashMap<String, IntHolder>();

	public GetOpt(String optionConfigs) {
		for (int i = 0; i < optionConfigs.length(); i++) {
			String option = optionConfigs.substring(i, i + 1);

			IntHolder config;
			if (m_optionConfigs.containsKey(option)) {
				config = m_optionConfigs.get(option);
			} else {
				config = new IntHolder();
				m_optionConfigs.put(option, config);
			}

			if (i < optionConfigs.length() - 1 && optionConfigs.charAt(i + 1) == ':') {
				config.value |= PARAMETRIC;
				i++;
			}
		}
	}

	public List<String> getArgs() {
		return m_args;
	}

	public boolean optionExists(String option) {
		return m_options.containsKey(option);
	}

	public String getOptionalParameter(String option) {
		return m_options.get(option);
	}

	public void parse(String[] args) {
		m_args.clear();
		m_options.clear();

		for (int i = 0; i < args.length; i++) {
			String arg = args[i];
			if (arg.startsWith("-")) {
				String option = arg.substring(1);
				if (m_optionConfigs.containsKey(option)) {
					if (i < args.length - 1
							&& (m_optionConfigs.get(option).value & PARAMETRIC) != 0) {
						m_options.put(option, args[i + 1]);
						i++;
					} else {
						m_options.put(option, "");
					}
				} else {
					m_args.add(arg);
				}
			} else {
				m_args.add(arg);
			}
		}
	}
}
